package com.example.server.controller;

import com.example.common.Result;
import com.example.server.entity.Book;
import com.example.server.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuyunbin
 * @since 2023-04-14
 */
@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("add")
    public Result add(@RequestBody Book book){
        Result result=new Result();
        result.setData(bookService.save(book));
        result.setFlag(true);
        result.setMessage("添加成功");
        return  result;
    }

    @GetMapping("")
    public Result list(){
        List<Book> list=new ArrayList<>();
        if(redisTemplate.hasKey("demo0414:server:list")){
            //把数据从redis中读取出来
            list = (ArrayList<Book> ) redisTemplate.opsForList().range("demo0414:server:list",0,-1);
        }else{
             list = bookService.list();
            //把list存到redis中，用list格式
            redisTemplate.opsForList().rightPushAll("demo0414:server:list", list);
        }
        return new Result(true,"查询成功",list);
    }
}
